#include "httpdowdloaddialog.h"
#include "ui_httpdowdloaddialog.h"
#include <QFileInfo>
#include <QFile>
#include <QMessageBox>
#include <QNetworkRequest>
#include <QDir>

HttpDowdloadDialog::HttpDowdloadDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::HttpDowdloadDialog)
{
    ui->setupUi(this);
    ui->lineEdit->setText("http://www.baidu.com");
    ui->stateLabel->setWordWrap(true);
    ui->dowloadButton->setDefault(true);
    ui->dowloadButton->setAutoDefault(false);

    progressDialog = new QProgressDialog(this);

    connect(ui->lineEdit, SIGNAL(textChanged(QString)),
            this, SLOT(enableDownloadButton()));
    connect(progressDialog, SIGNAL(canceled()),
            this, SLOT(cancleDownload()));
}

HttpDowdloadDialog::~HttpDowdloadDialog()
{
    delete ui;
}

void HttpDowdloadDialog::startRequest(QUrl url)
{
    reply = manager->get(QNetworkRequest(url));
    connect(reply, SIGNAL(readyRead()), this, SLOT(httpReadyRead()));
    connect(reply, SIGNAL(downloadProgress(qint64,qint64)),
            this, SLOT(httpUpdateDownlaodProgress(qint64,qint64)));
    connect(reply, SIGNAL(finished()), this, SLOT(httpDownloadFinished()));
    progressDialog->show();
}

void HttpDowdloadDialog::httpReadyRead()
{
    if (file){
        file->write(reply->readAll());
    }
}

void HttpDowdloadDialog::httpDownloadFinished()
{
    if (httpRequestAbort){
        if (file){
            file->close();
            file->remove();
            delete file;
            file = 0;
        }
        reply->deleteLater();
        progressDialog->hide();
        return;
    }

    //
    progressDialog->hide();
    file->flush();
    file->close();

    QVariant redirectionTarget = reply->attribute(QNetworkRequest::RedirectionTargetAttribute);
    if (reply->error()){
        file->remove();
        QMessageBox::information(this, tr("Http"),
            tr("Download faild: %1.").arg(reply->errorString()));
        ui->dowloadButton->setEnabled(true);
    }else if (!redirectionTarget.isNull()){
        QUrl newUrl = url.resolved(redirectionTarget.toUrl());
        if (QMessageBox::question(this, tr("Http"), tr("Redirect to %1 ?").arg(url.toString()),
                                  QMessageBox::Yes|QMessageBox::No) == QMessageBox::Yes){
           url = newUrl;
           reply->deleteLater();
           file->open(QIODevice::WriteOnly);
           file->resize(0);
           startRequest(url);
           return;
        }
    }else{
        QString fileName = QFileInfo(QUrl(ui->lineEdit->text()).path()).fileName();
        ui->stateLabel->setText(tr("Download %1 to %2").arg(fileName).arg(QDir::currentPath()));
        ui->dowloadButton->setEnabled(true);
    }

    reply->deleteLater();
    delete file;
    file = 0;
    manager = 0;
}

void HttpDowdloadDialog::httpUpdateDownlaodProgress(qint64 bytesRead, qint64 totalBytes)
{
    if (httpRequestAbort)
        return;
    progressDialog->setMaximum(totalBytes);
    progressDialog->setValue(bytesRead);
}

void HttpDowdloadDialog::enableDownloadButton()
{
    ui->dowloadButton->setEnabled(!ui->lineEdit->text().isEmpty());
}

void HttpDowdloadDialog::cancleDownload()
{
    ui->label->setText("Download cancled");
    httpRequestAbort = true;
    reply->abort();
    ui->dowloadButton->setEnabled(true);
}

void HttpDowdloadDialog::on_quitButton_clicked()
{
    this->close();
}

void HttpDowdloadDialog::on_dowloadButton_clicked()
{
    manager = new QNetworkAccessManager(this);
    url = QUrl(ui->lineEdit->text());
    QFileInfo info(url.path());
    QString FileName = info.fileName();
    if (FileName.isEmpty()){
        FileName ="index.html";
    }

    if (QFile::exists(FileName)){
        if (QMessageBox::question(this, tr("Http"),
                tr("There already exists a file called %1 in "
                "the current directory. Overwrite?").arg(FileName),
                QMessageBox::Yes|QMessageBox::No, QMessageBox::No)
                == QMessageBox::No)
            return;
        QFile::remove(FileName);
    }
    file = new QFile(FileName);
    if (!file->open(QIODevice::WriteOnly)){
        QMessageBox::information(this, tr("Http"),
            tr("Unable to save the file %1 : %2")
            .arg(FileName).arg(file->errorString()));
        delete file;
        file = 0;
        return;
    }

    httpRequestAbort = false;

    progressDialog->setWindowTitle(tr("Http"));
    progressDialog->setLabelText(tr("Downloading %1 ...").arg(FileName));
    ui->dowloadButton->setEnabled(false);
    startRequest(url);
}

void HttpDowdloadDialog::on_lineEdit_returnPressed()
{
    on_dowloadButton_clicked();
}
